import axios from 'axios';
import { history } from 'umi';
function login(data) {
  return axios.post('/api/login', data);
}

export default {
  namespace: 'user',
  state: JSON.parse(sessionStorage.getItem('user')) || {},
  effects: {
    *login(action, { call, put }) {
      try {
        const res = yield call(login, action.payload);
        if (res.data.code >= 0) {
          yield put({ type: 'saveUser', payload: res.data.data });
          sessionStorage.setItem('user', JSON.stringify(res.data.data));
          history.push('/');
        }
      } catch (error) {
        alert('登录失败:' + error.msg);
      }
    },
  },
  reducers: {
    saveUser(state, action) {
      return action.payload;
    },
    removeUser(state, action) {
      history.push('/login');
      sessionStorage.removeItem('user');
      return {};
    },
  },
};
